using System.Text;
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using Csla.Validation;
using BA.DAL;
using BA;

namespace BlazeApps.Library.Polls
{
    [Serializable()]
    public class PollAnswerDetail : Csla.BusinessBase<PollAnswerDetail>
    {
        private BlazeApps.Library.ConfigSettings Config = new BlazeApps.Library.ConfigSettings();
        private BA.DAL.DBUtility DAL = new BA.DAL.DBUtility();
        private Procedures Procs = new Procedures();

        #region Business Properties and Methods

        //declare members
        private Guid _pollId = Guid.Empty;
        private Guid _answerId = Guid.NewGuid();
        private string _answerText = string.Empty;
        private int _answerCount = 0;

        public Guid PollId
        {
            get
            {
                CanReadProperty("PollId", true);
                return _pollId;
            }
            set
            {
                CanWriteProperty("PollId", true);
                if (!_pollId.Equals(value))
                {
                    _pollId = value;
                    PropertyHasChanged("PollId");
                }
            }
        }

        [System.ComponentModel.DataObjectField(true, false)]
        public Guid AnswerId
        {
            get
            {
                CanReadProperty("AnswerId", true);
                return _answerId;
            }
        }

        public string AnswerText
        {
            get
            {
                CanReadProperty("AnswerText", true);
                return _answerText;
            }
            set
            {
                CanWriteProperty("AnswerText", true);
                if (value == null)
                    value = string.Empty;
                if (!_answerText.Equals(value))
                {
                    _answerText = value;
                    PropertyHasChanged("AnswerText");
                }
            }
        }

        public int AnswerCount
        {
            get
            {
                CanReadProperty("AnswerCount", true);
                return _answerCount;
            }
            set
            {
                CanWriteProperty("AnswerCount", true);
                if (!_answerCount.Equals(value))
                {
                    _answerCount = value;
                    PropertyHasChanged("AnswerCount");
                }
            }
        }

        protected override object GetIdValue()
        {
            return _answerId;
        }

        #endregion //Business Properties and Methods

        #region Validation Rules
        private void AddCustomRules()
        {
            //add custom/non-generated rules here...
        }

        private void AddCommonRules()
        {
            //
            // AnswerText
            //
            ValidationRules.AddRule(CommonRules.StringRequired, "AnswerText");
            ValidationRules.AddRule(CommonRules.StringMaxLength, new CommonRules.MaxLengthRuleArgs("AnswerText", 250));
        }

        protected override void AddBusinessRules()
        {
            AddCommonRules();
            AddCustomRules();
        }
        #endregion //Validation Rules

        #region Authorization Rules
        protected override void AddAuthorizationRules()
        {
            //TODO: Define authorization rules in PollAnswerDetail
            //AuthorizationRules.AllowRead("PollId", "PollAnswerDetailReadGroup");
            //AuthorizationRules.AllowRead("AnswerId", "PollAnswerDetailReadGroup");
            //AuthorizationRules.AllowRead("AnswerText", "PollAnswerDetailReadGroup");
            //AuthorizationRules.AllowRead("AnswerCount", "PollAnswerDetailReadGroup");

            //AuthorizationRules.AllowWrite("PollId", "PollAnswerDetailWriteGroup");
            //AuthorizationRules.AllowWrite("AnswerText", "PollAnswerDetailWriteGroup");
            //AuthorizationRules.AllowWrite("AnswerCount", "PollAnswerDetailWriteGroup");
        }


        public static bool CanGetObject()
        {
            //TODO: Define CanGetObject permission in PollAnswerDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("PollAnswerDetailViewGroup"))
            //	return true;
            //return false;
        }

        public static bool CanAddObject()
        {
            //TODO: Define CanAddObject permission in PollAnswerDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("PollAnswerDetailAddGroup"))
            //	return true;
            //return false;
        }

        public static bool CanEditObject()
        {
            //TODO: Define CanEditObject permission in PollAnswerDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("PollAnswerDetailEditGroup"))
            //	return true;
            //return false;
        }

        public static bool CanDeleteObject()
        {
            //TODO: Define CanDeleteObject permission in PollAnswerDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("PollAnswerDetailDeleteGroup"))
            //	return true;
            //return false;
        }
        #endregion //Authorization Rules

        #region Factory Methods
        private PollAnswerDetail()
        { /* require use of factory method */
        }

        public static PollAnswerDetail NewPollAnswerDetail()
        {
            if (!CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a PollAnswerDetail");
            return DataPortal.Create<PollAnswerDetail>();
        }

        public static PollAnswerDetail GetPollAnswerDetail(Guid answerId)
        {
            if (!CanGetObject())
                throw new System.Security.SecurityException("User not authorized to view a PollAnswerDetail");
            return DataPortal.Fetch<PollAnswerDetail>(new Criteria(answerId));
        }

        public static void DeletePollAnswerDetail(Guid PollId, Guid answerId)
        {
            if (!CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a PollAnswerDetail");
            DataPortal.Delete(new Criteria(PollId, answerId));
        }

        public override PollAnswerDetail Save()
        {
            if (IsDeleted && !CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a PollAnswerDetail");
            else if (IsNew && !CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a PollAnswerDetail");
            else if (!CanEditObject())
                throw new System.Security.SecurityException("User not authorized to update a PollAnswerDetail");

            return base.Save();
        }

        #endregion //Factory Methods

        #region Data Access

        #region Criteria

        [Serializable()]
        private class Criteria
        {
            public Guid PollId;
            public Guid AnswerId;

            public Criteria(Guid answerId)
            {
                this.AnswerId = answerId;
            }

            public Criteria(Guid PollId, Guid answerId)
            {
                this.PollId = PollId;
                this.AnswerId = answerId;
            }
        }

        #endregion //Criteria

        #region Data Access - Create
        [RunLocal]
        protected override void DataPortal_Create()
        {
            ValidationRules.CheckRules();
        }

        #endregion //Data Access - Create

        #region Data Access - Fetch
        private void DataPortal_Fetch(Criteria criteria)
        {
            ExecuteFetch(criteria);
        }

        private void ExecuteFetch(Criteria criteria)
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            DAL.AddParameter("@AnswerId", criteria.AnswerId);

            using(SafeDataReader dr = new SafeDataReader(DAL.ExecuteReader(Procs.GetPollAnswerByAnswerID.ToString().Trim(), CommandType.Text, ConnectionState.Open)))
            {
                FetchObject(dr);
                ValidationRules.CheckRules();

                //load child object(s)
                FetchChildren(dr);
            }
        }

        private void FetchObject(SafeDataReader dr)
        {
            dr.Read();
            _answerId = dr.GetGuid("AnswerId");
            _answerText = dr.GetString("AnswerText");
        }

        private void FetchChildren(SafeDataReader dr)
        {
        }
        #endregion //Data Access - Fetch

        #region Data Access - Insert
        protected override void DataPortal_Insert()
        {
            ExecuteInsert();
        }

        private void ExecuteInsert()
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddInsertParameters(ref DAL);

            DAL.ExecuteNonQuery(Procs.InsertPollAnswer.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddInsertParameters(ref BA.DAL.DBUtility DAL)
        {
            DAL.AddParameter("@PollId", _pollId);
            DAL.AddParameter("@AnswerID", _answerId);
            DAL.AddParameter("@AnswerText", _answerText);
        }
        #endregion //Data Access - Insert

        #region Data Access - Update
        protected override void DataPortal_Update()
        {
            if (base.IsDirty)
            {
                ExecuteUpdate();
            }
        }

        private void ExecuteUpdate()
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddUpdateParameters(ref DAL);

            DAL.ExecuteNonQuery(Procs.UpdatePollAnswer.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddUpdateParameters(ref BA.DAL.DBUtility DAL)
        {
            DAL.AddParameter("@AnswerId", _answerId);
            DAL.AddParameter("@AnswerText", _answerText);
        }

        private void UpdateChildren(SqlConnection cn)
        {
        }
        #endregion //Data Access - Update

        #region Data Access - Delete
        protected override void DataPortal_DeleteSelf()
        {
            DataPortal_Delete(new Criteria(_answerId));
        }

        private void DataPortal_Delete(Criteria criteria)
        {
            ExecuteDelete(criteria);
        }

        private void ExecuteDelete(Criteria criteria)
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddDeleteParameters(ref DAL, criteria);

            DAL.ExecuteNonQuery(Procs.DeletePollAnswer.ToString().Trim(), CommandType.Text, ConnectionState.Open);

            UpdateAnswerCountOnDelete(criteria);
        }

        private void AddDeleteParameters(ref BA.DAL.DBUtility DAL, Criteria criteria)
        {
            DAL.AddParameter("@PollId", criteria.PollId);
            DAL.AddParameter("@AnswerId", criteria.AnswerId);
        }

        private void UpdateAnswerCountOnDelete(Criteria criteria)
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            DAL.AddParameter("@PollId", criteria.PollId);
            DAL.AddParameter("@AnswerId", criteria.AnswerId);

            DAL.ExecuteNonQuery(Procs.UpdateVoteCountOnAnswerDelete.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }
        #endregion //Data Access - Delete
        #endregion //Data Access
    }
}
